#include "head_c.h"

int upload(const user_t* status, const portocol_t* portocol, int socket_fd)
{


    printf("file name%s  %ld \n", portocol->arg,  strlen(portocol->arg));

    char file_name[100] = {0};
    int index = 0;
    for(int i=0; i<strlen(portocol->arg); i++){
        if(portocol->arg[i] == '&'){
            index = i+1;
        }else if(portocol->arg[i] == 0){
            break;
        }
    }

    for(int i=0; i<strlen(portocol->arg); i++){
        if(portocol->arg[i+index] != 0){
            file_name[i] = portocol->arg[i+index];
        }else{
            break;
        }
    }
    printf("file_name : %s  %ld \n", file_name, strlen(file_name));

    // 打开文件获得文件大小
    int file_fd = open(file_name, O_RDWR);
    if(file_fd == -1){
        perror("open failed!\n");
        exit(1);
    }

    struct stat st;
    if(fstat(file_fd, &st) == -1){
        perror("fstat failed!\n");
        exit(1);
    }

    send(socket_fd, &st.st_size, sizeof(off_t), MSG_NOSIGNAL);


    int flag =-1; // 0全新上传， 1存在  2断点

    recv(socket_fd, &flag, sizeof(int), 0);

    if(flag == 1){
        printf("文件已经存在不要重复上传\n");
        return  0;
    }

    // TODO: --------------------

    if(flag ==0){
        // 全新上传
        sendfile(socket_fd,file_fd, 0,st.st_size   );
    }else{
        // 断点上传
        off_t upload_size;
        recv(socket_fd, &upload_size, sizeof(off_t), 0);
        printf("upload_size： %ld \n", upload_size);

        void* mapped = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, file_fd, 0);
        // send(socket_fd, );
        int ret = send(socket_fd, mapped+upload_size, st.st_size - upload_size, MSG_NOSIGNAL);
        printf("send ret: %d \n", ret);
        munmap(mapped, st.st_size);
    }

    return 0;
}

